<?php

namespace App\Http\Controllers\Store\User;

use App\Exceptions\LoginException;
use App\Exceptions\SmsException;
use App\Exceptions\UserException;
use App\Services\Store\User\UserService;
use Exception;
use Illuminate\Http\JsonResponse;

class UserController extends BaseUserController
{
    protected UserService $userService;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->userService = $this->loadService('Store\User\UserService');
    }

    /**
     * 申请入住(注册)
     * @return JsonResponse
     * @throws SmsException
     * @throws UserException
     */
    public function register(): JsonResponse
    {
        $rule = [
            'realName' => 'required|string|min:1',
            'password' => 'required|string|min:6',
            'qrPassword' => 'required|string|min:6',
            'phone' => 'required|string|min:1',
            'idCard' => 'required|string|min:1',
            'ranchName' => 'required|string|min:1',
            'provinceId' => 'required|integer|min:1',
            'cityId' => 'required|integer|min:1',
            'regionId' => 'required|integer|min:1',
            'address' => 'required|string|min:1',
            'verifyCode' => 'required|string|min:6',
            'frontImgUrl' => 'required|string|min:1',
            'backImgUrl' => 'required|string|min:1',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->userService->register($this->params);
        return outputJsonResult();
    }

    /**
     * 登录
     * @return JsonResponse
     * @throws LoginException
     */
    public function login(): JsonResponse
    {
        $rule = [
            'phone' => 'required|string|min:1',
            'password' => 'required|string|min:6',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $result = $this->userService->login($this->params);
        return outputJsonResult($result);
    }

    /**
     * 忘记密码
     * @return JsonResponse
     * @throws Exception
     */
    public function resetPassword(): JsonResponse
    {
        $rule = [
            'phone' => 'required|string|min:1',
            'verifyCode' => 'required|string|min:6',
            'password' => 'required|string|min:6',
            'qrPassword' => 'required|string|min:6',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonError();
        }

        $this->userService->resetPassword($this->params);
        return outputJsonResult();
    }

}
